<?php
  
  class memcacheAPI {
	
	/* Define the class constructor */
	function __construct() {
	  $this->connection = new Memcache;
	  $this->log = new logAPI();
	  $this->date = date('Y-m-d H:i:s');
	  $this->log->Logger("[[".$this->date."]] "."New Instance Created<br/>\n");
	}
	
	/*  connect() connects to the Memcache Server  */
	/* returns TRUE if connection established */
	/* returns FALSE if connection failed */
	function connect() {
	  $memHost = "localhost";
	  $memPort = 11211;	  
	  if($this->connection->connect($memHost,$memPort)) {
	    $this->log->Logger("[[".$this->date."]] "."Connection established with memcache server<br/>\n");
		return TRUE;
	  }
	  else {
	    $this->log->Logger("[[".$this->date."]] "."Connection failed to establish with memcache server<br/>\n");
	    return FALSE;
	  }
	}
	
	/* close() will disconnet from Memcache Server */
	function close() {
	  if($this->connection->close()) {
	    $this->log->Logger("[[".$this->date."]] "."Connection closed with memcache server<br/>\n");
	    $this->log->Logger("=================================================================================================<br/>\n\n");
	    return TRUE;
	  }
	  else {
	    $this->log->Logger("[[".$this->date."]] "."Connection didn't close with memcache server<br/>\n");
		$this->log->Logger("=======================================================================================================<br/>\n\n");
	    return FALSE;
	  }
	}
	
	/* getCache() function will fetch the passed $query resultset from cache */
	/* returned resultset is null if $query not found in cache */
	function getCache($query) {
	  /* Generate the key corresponding to query */
	  $key = base64_encode($query);
	  
	  /* Get the resultset from cache */
	  $resultset = $this->connection->get($key);
	  
	  /* Unserialize the result if found in cache */
	  if($resultset != null) {
	    $this->log->Logger("[[".$this->date."]] "."Query ".$query." was found already cached<br/>\n");
	    $resultset = unserialize($resultset);
	  }
	  else {
	    $this->log->Logger("[[".$this->date."]] "."Query ".$query." was not found cached in memcache server<br/>\n");
	  }
	  return $resultset;
	}
	
	/* setCache() function will set the serialized resultset on Memcache Server */
	function setCache($query,$resultset,$useCompression=0,$ttl=600) {
	  /* Generate the key corresponding to query */
	  $key = base64_encode($query);
	  
	  /* Set the value on Memcache Server */
	  $resultset = serialize($resultset);
	  if($this->connection->set($key,$resultset,$useCompression,$ttl)) {
	    $this->log->Logger("[[".$this->date."]] "."Query ".$query." was cached<br/>\n");
		return TRUE;
	  }
	  else {
	    $this->log->Logger("[[".$this->date."]] "."Query ".$query." was not able to cache<br/>\n");
		return FALSE;
	  }
	}
	
  }

?>